
import UIKit
import SVProgressHUD

class XSOAuthController: UIViewController, UIWebViewDelegate {
    
    override func loadView() {
        super.loadView()
        
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")

        let request = NSURLRequest(URL: NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=858911086&redirect_uri=http://www.baidu.com")!)
        webView.loadRequest(request)
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        let url = request.URL?.absoluteString
        
        if !(url?.hasPrefix("www.baidu.com") != nil)
        {
            return true
        }
        
        // query就是问号后面的东西
        if let query = request.URL?.query
        {
            if query.hasPrefix("code=")
            {
                let queryNs = query as NSString
                let code = queryNs.substringFromIndex("code=".characters.count)
                
                getAccessToken(code)
                
                return false
            }
            else
            {
                return true
            }
        }
        
        return true
    }
    
//    App Key：858911086
//    App Secret：c863d2f916b14e0e698f87571e013483
    private func getAccessToken(code: NSString)
    {
        let parmant = ["client_id": "858911086", "client_secret": "c863d2f916b14e0e698f87571e013483", "grant_type": "authorization_code", "code": code, "redirect_uri": "www.baidu.com"]
        
        XSNetworkTool.sharedNetworkTool.postRequestWithParmant(parmant, url: "https://api.weibo.com/oauth2/access_token") { (result, error) -> () in
            
//            let account = XSUserAccount.loadAccountInfor(result as [String: AnyObject]!)
//            account.saveUserAccount()
//            
//            if (account.loadUserAccount() != nil)
//            {
//                (UIApplication.sharedApplication().delegate as! AppDelegate).switchVc(XSWeclomeController() as UIViewController)
//            }
        }
    }
    
    func webViewDidStartLoad(webView: UIWebView)
    {
        SVProgressHUD.showWithStatus("正在加载中.....", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView)
    {
        SVProgressHUD.dismiss()
    }
    
    func autoFill()
    {
        let js = "document.getElementById('userId').value='2330216158@qq.com'; document.getElementById('passwd').value='a123456';"
        
        // 让webView来执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    func close()
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    private lazy var webView: UIWebView = UIWebView()
}
